<template>
  <div>
    <div class="question-filtrate">
      <div class="head-reminder">
        <div class="left-explain">说明：目前支持学科和关键字条件筛选</div>
        <el-button type="success" icon="el-icon-edit" @click="toAdd"
          >新增试题</el-button
        >
      </div>
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科" prop="isSubjectsList">
          <el-select
            v-model="ruleForm.isSubjectsList"
            placeholder="请选择"
            @focus="getSubjectsList"
            @change="subjectChangeFn"
          >
            <el-option
              v-for="item in subjectsList"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级目录" prop="isSubjectsDetail">
          <el-select
            v-model="ruleForm.isSubjectsDetail"
            placeholder="请选择"
            @focus="getSubjectsDetail"
          >
            <el-option
              v-for="item in subjectsDetail"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="isTagsList">
          <el-select
            v-model="ruleForm.isTagsList"
            placeholder="请选择"
            @focus="getTagsList"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.id"
              :label="item.tagName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keyWords">
          <el-input
            v-model="ruleForm.keyWords"
            placeholder="根据关键词搜索"
            @change="changeKeyWords"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题类型" prop="isQuestionType">
          <el-select v-model="ruleForm.isQuestionType" placeholder="请选择">
            <el-option
              v-for="(item, index) in questionType"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度" prop="isDifficulty">
          <el-select v-model="ruleForm.isDifficulty" placeholder="请选择">
            <el-option
              v-for="(item, index) in difficulty"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="isDirection">
          <el-select v-model="ruleForm.isDirection" placeholder="请选择">
            <el-option
              v-for="(item, index) in direction"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="录入人" prop="isUserList">
          <el-select
            v-model="ruleForm.isUserList"
            placeholder="请选择"
            @focus="getUserList"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目备注" prop="articleComment">
          <el-input v-model="ruleForm.articleComment"></el-input>
        </el-form-item>
        <el-form-item label="企业简介" prop="enterpriseAbbreviation">
          <el-input v-model="ruleForm.enterpriseAbbreviation"></el-input>
        </el-form-item>

        <el-form-item label="城市" prop="isProvinces">
          <el-select
            v-model="ruleForm.isProvinces"
            placeholder="请选择"
            @change="cityChangeFn"
            class="city"
          >
            <el-option
              v-for="(item, index) in provincesList"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>

          <el-select
            v-model="ruleForm.isCitys"
            placeholder="请选择"
            class="city"
          >
            <el-option
              v-for="(item, index) in citysList"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetForm('ruleForm')">清除</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">
            搜索
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="question-table">
      <!-- 审核状态 -->
      <div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="全部" name="first"></el-tab-pane>
          <el-tab-pane label="待审核" name="second"></el-tab-pane>
          <el-tab-pane label="已审核" name="third"></el-tab-pane>
          <el-tab-pane label="已拒绝" name="fourth"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 一共几条数据 -->
      <div>
        <el-alert :title="'数据一共' + totalList + '条'" type="info" show-icon>
        </el-alert>
      </div>

      <!-- 试题表格 -->
      <el-table :data="choiceQuestions" style="width: 100%" stripe>
        <el-table-column prop="number" label="试题编号" width="230">
        </el-table-column>
        <el-table-column prop="subject" label="学科" width="100">
        </el-table-column>
        <el-table-column prop="catalog" label="目录" width="100">
        </el-table-column>
        <el-table-column prop="questionType" label="题型" width="90">
          <template slot-scope="scope">
            <p v-if="scope.row.questionType == '1'">单选</p>
            <p v-if="scope.row.questionType == '2'">多选</p>
            <p v-if="scope.row.questionType == '3'">简答</p>
          </template>
        </el-table-column>
        <el-table-column label="题干" width="200">
          <template slot-scope="scope">
            <p v-html="scope.row.question"></p>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间" width="180">
          <template slot-scope="scope">
            {{ scope.row.addDate | relativeTime }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="90">
          <template slot-scope="scope">
            <p v-if="scope.row.difficulty == '1'">简单</p>
            <p v-if="scope.row.difficulty == '2'">一般</p>
            <p v-if="scope.row.difficulty == '3'">困难</p>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" width="100">
        </el-table-column>
        <el-table-column prop="chkState" label="审核状态" width="90">
          <template slot-scope="scope">
            <p v-if="scope.row.chkState == '0'">待审核</p>
            <p v-if="scope.row.chkState == '1'">通过</p>
            <p v-if="scope.row.chkState == '2'">拒绝</p>
          </template>
        </el-table-column>
        <el-table-column prop="chkRemarks" label="审核意见" width="120">
        </el-table-column>
        <el-table-column prop="chkUser" label="审核人" width="100">
        </el-table-column>

        <el-table-column label="操作" width="190" fixed="right">
          <template slot-scope="scope">
            <div>
              <el-button
                class="table_btn"
                @click="preview(scope.row)"
                type="text"
                size="mini"
                >预览</el-button
              >
              <el-button
                class="table_btn"
                :class="{ disabled: scope.row.chkState !== 0 }"
                :disabled="scope.row.chkState !== 0"
                type="text"
                size="mini"
                @click="checkQuestion(scope.row)"
                >审核</el-button
              >
              <el-button
                class="table_btn"
                @click="toEdit(scope.row)"
                type="text"
                size="mini"
                :class="{ disabled: scope.row.publishState === 1 }"
                :disabled="scope.row.publishState === 1"
                >修改</el-button
              >
              <el-button
                class="table_btn"
                @click="choiceAdd(scope.row, $event)"
                type="text"
                size="mini"
                >{{ scope.row.publishState === 1 ? "下架" : "上架" }}</el-button
              >
              <el-button
                class="table_btn"
                @click="removeQuestion(scope.row)"
                type="text"
                size="mini"
                :class="{ disabled: scope.row.publishState === 1 }"
                :disabled="scope.row.publishState === 1"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- layout 要在页面上显示的内容    total 总页数      prev表示上一页，next为下一页，pager表示页码列表 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pagesize"
          layout=" prev, pager, next, sizes, jumper"
          :total="totalList"
          background
        >
        </el-pagination>
      </div>

      <!-- 预览弹框 -->
      <QuestionPreview
        :dialogVisible="dialogVisible"
        @close="dialogVisible = false"
        :questionItem="questionItem"
      />

      <!-- 审核弹框 -->
      <QuestionCheck
        :dialogVisible="checkDialogVisible"
        @close="checkFn"
        :questionItem="questionItem"
      ></QuestionCheck>
    </div>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys.js'
import { difficulty, questionType, direction } from '@/api/hmmm/constants.js'
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/directorys.js'
import { list as tagsList } from '@/api/hmmm/tags.js'
import { simple as userList } from '@/api/base/users.js'
// 表格数据choiceQuestionsFn
import { detail as questionDetail, choicePublish, remove as questionRemove, choice as choiceQuestionsFn } from '@/api/hmmm/questions.js'
import QuestionPreview from './my-questions-preview.vue'
import QuestionCheck from './questions-check.vue'
export default {
  components: { QuestionPreview, QuestionCheck },
  data () {
    return {
      ruleForm: {
        isSubjectsList: null, // 学科
        isSubjectsDetail: null, // 二级目录（学科详情）
        isTagsList: '', // 标签
        keyWords: '', // 关键字
        isQuestionType: null, // 试题类型
        isDifficulty: '', // 难度
        isDirection: '', // 方向
        isUserList: '', // 录入人
        articleComment: '', // 题目备注
        enterpriseAbbreviation: '', // 企业简称
        isProvinces: '', // 城市
        isCitys: '' // 地区
      },
      subjectsList: [], // 学科
      subjectsDetail: [], // 二级目录（学科详情）
      tagsList: [], // 标签
      questionType: questionType, // 试题类型
      difficulty: difficulty, // 难度
      direction: direction, // 方向
      userList: [], // 录入人
      provincesList: provinces(), // 城市
      citysList: [], // 地区

      // 表格数据
      activeName: 'first',
      choiceQuestions: [],
      questionFiltrate: {}, // 接受question-filtrate传过来的选择条件
      page: 1, // 当前页数
      pagesize: 5, // 页尺寸
      totalList: '', // 总条数
      chkState: '', // 审核状态

      dialogVisible: false, // 试题预览
      checkDialogVisible: false, // 审核试题的对话框
      questionItem: {} // 预览时传入子组件的试题
    }
  },
  created () {
    this.chkState = null // 清空审核状态
    this.getChoiceQuestions() // 重新获取数据
  },
  methods: {
    // 🌈 点击修改
    toAdd (row) {
      this.$router.push({
        path: 'new'
      })
    },

    // 根据城市获取地区
    cityChangeFn () {
      this.citysList = citys(this.ruleForm.isProvinces)
    },

    // 获取学科
    async getSubjectsList () {
      const { data } = await simple()
      // console.log(data);
      this.subjectsList = data
    },
    // 学科框数据发生改变后
    subjectChangeFn () {
      this.ruleForm.isSubjectsDetail = '' // 清空二级目录
      this.ruleForm.isTagsList = '' // 清空标签
    },

    // 获取二级目录
    async getSubjectsDetail () {
      const { data } = await list({
        subjectID: this.ruleForm.isSubjectsList
      })
      // console.log(this.ruleForm.isSubjectsList);
      // console.log(data.items);
      this.subjectsDetail = data.items
    },

    // 获取标签
    async getTagsList () {
      const { data } = await tagsList({
        subjectID: this.ruleForm.isSubjectsList,
        pagesize: 100
      })
      console.log(data.items)
      this.tagsList = data.items
    },

    // 关键字发生改变后
    changeKeyWords () {
      this.ruleForm.isUserList = ''
    },

    async getUserList () {
      const { data } = await userList({
        keyword: this.ruleForm.keyWords
      })
      console.log(data)
      this.userList = data
    },

    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 提交
          this.getChoiceQuestions()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()

      // 手动清除地区里面的数据
      this.ruleForm.isCitys = ''
      this.getChoiceQuestions()
    },

    // 表格里面的数据

    // 审核状态
    handleClick (tab, event) {
      ''
      if (parseInt(tab.index) === 0) {
        this.chkState = null
      } else if (parseInt(tab.index) === 1) {
        this.chkState = 0
      } else if (parseInt(tab.index) === 2) {
        this.chkState = 1
      } else if (parseInt(tab.index) === 3) {
        this.chkState = 2
      }
      console.log(this.chkState)
      // 更新列表
      this.getChoiceQuestions()
    },
    checkFn () {
      this.checkDialogVisible = false
      this.getChoiceQuestions()
    },

    // 右侧操作
    // 🌈 预览
    async preview (item) {
      // 显示对话框
      const { data } = await questionDetail({ id: item.id })
      console.log(data)
      data.questionType = item.questionType
      data.subject = item.subject
      this.dialogVisible = true
      // 传入试题
      this.questionItem = data
    },
    // 🌈 审核试题
    checkQuestion (item) {
      this.checkDialogVisible = true
      this.questionItem = item
    },
    checkClose () {
      this.checkDialogVisible = false
      this.getChoiceQuestions()
    },

    // 🌈 点击修改
    toEdit (row) {
      this.$router.push({
        path: 'new',
        query: {
          id: row.id
        }
      })
    },

    // 🌈 上架和下架试题
    async choiceAdd (item, e) {
      const result = await this.$confirm(
        '您确认' + e.target.innerText + '这道题目吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      ).catch((err) => err)

      let data = {} // 下面用来接收返回的结果

      // 如果确认就加上架/下架 否则什么都不做
      if (result === 'confirm') {
        switch (e.target.innerText) {
          case '上架':
            data = await choicePublish({
              id: item.id,
              publishState: 1
            })
            break

          case '下架':
            data = await choicePublish({
              id: item.id,
              publishState: 0
            })
            break
        }

        if (data.status === 200) {
          this.$message.success(e.target.innerText + '成功')
        }
        // 更新题库列表
        this.getChoiceQuestions()
      }
    },

    // 🌈 删除题库中的题
    async removeQuestion (item) {
      // 提示框
      const result = await this.$confirm(
        '此操作将永久删除该题目, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果确认删除执行删除逻辑
      if (result === 'confirm') {
        const data = await questionRemove(item)

        // 如果状态码是200表示删除成功
        if (data.status === 200) {
          this.getChoiceQuestions()
          return this.$message.success('删除成功')
        }
      }
    },

    // 分页
    // 每页几条
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.getChoiceQuestions()
    },
    // 第几页
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getChoiceQuestions()
    },

    // 获取精选题库数据
    async getChoiceQuestions () {
      console.log(this.chkState)
      console.log('更新列表，获取数据')
      // console.log('学科ID', this.ruleForm.isSubjectsList)
      const { data } = await choiceQuestionsFn({
        page: this.page,
        pagesize: this.pagesize,
        subjectID: this.ruleForm.isSubjectsList,
        difficulty: this.ruleForm.isDifficulty,
        questionType: this.ruleForm.isQuestionType,
        tags: this.ruleForm.isTagsList,
        province: this.ruleForm.isProvinces,
        city: this.ruleForm.isCitys,
        keyword: this.ruleForm.keyWords,
        remarks: this.ruleForm.articleComment,
        shortName: this.ruleForm.enterpriseAbbreviation,
        direction: this.ruleForm.isDirection,
        creatorID: this.ruleForm.isUserList,
        catalogID: this.ruleForm.isSubjectsDetail,
        chkState: this.chkState // 审核
      })
      console.log(data)
      this.totalList = data.counts
      console.log(data.counts)
      this.choiceQuestions = data.items
    }
  }
}
</script>

<style scoped>
.head-reminder {
  display: flex;
  justify-content: space-between;
  height: 32px;
  margin-bottom: 15px;
  align-items: center;
  font-size: 12px;
  color: pink;
}
.el-button--medium {
  font-size: 12px;
}
.question-filtrate .el-form {
  display: flex;
  flex-wrap: wrap;
}
.question-filtrate .el-form-item {
  width: 310px;
}
.city {
  width: 100px;
}
.block {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
